package com.iot.gateway.tsl.controller;

import com.iot.gateway.tsl.qo.ProductQo;
import com.iot.gateway.tsl.service.TslProductService;
import com.iot.gateway.utils.ApiResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品 Profile 管理接口
 */
@RestController
@RequestMapping("/api/product")
@Tag(name = "产品管理")
public class TslProductController {

    private final TslProductService productService;

    public TslProductController(TslProductService productService) {
        this.productService = productService;
    }

    @Operation(summary = "新增产品 Profile", description = "为系统新增一个产品物模型 Profile")
    @PostMapping("/add")
    public ApiResult<Void> addProduct(
            @Parameter(description = "产品信息，包含 productKey 和 version", required = true)
            @RequestBody ProductQo productQo) {

        productService.addProduct(productQo);
        return ApiResult.success();
    }

    @Operation(summary = "更新产品 Profile", description = "更新指定产品的物模型版本号")
    @PostMapping("/update/{productKey}")
    public ApiResult<Void> updateProduct(
            @Parameter(description = "产品 Key", required = true, example = "abc123XYZ")
            @PathVariable String productKey,
            @Parameter(description = "新版物模型信息，version 字段必填", required = true)
            @RequestBody ProductQo productQo) {

        productQo.setProductKey(productKey);
        productService.updateProduct(productQo);
        return ApiResult.success();
    }

    @Operation(summary = "删除产品 Profile", description = "删除指定产品的物模型 Profile")
    @PostMapping("/del/{productKey}")
    public ApiResult<Void> deleteProduct(
            @Parameter(description = "产品 Key", required = true, example = "abc123XYZ")
            @PathVariable String productKey) {

        productService.deleteProduct(productKey);
        return ApiResult.success();
    }

    @Operation(summary = "查询单个产品 Profile", description = "获取指定产品的物模型 Profile")
    @GetMapping("/select/{productKey}")
    public ApiResult<ProductQo> getProduct(
            @Parameter(description = "产品 Key", required = true, example = "abc123XYZ")
            @PathVariable String productKey) {

        ProductQo qo = productService.getProduct(productKey);
        return qo == null
                ? ApiResult.fail(404, "产品不存在")
                : ApiResult.success(qo);
    }

    @Operation(summary = "查询所有产品 Profile", description = "获取系统中所有已配置的产品 Profile 列表")
    @GetMapping("/selectAll")
    public ApiResult<List<ProductQo>> listProducts() {
        List<ProductQo> list = productService.listProducts();
        return ApiResult.success(list);
    }
}
